'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Loader2 } from 'lucide-react'
import ReactECharts from 'echarts-for-react'

interface UserProfile {
  RHR: number
  MHR: number
  HRR: number
  age: number
}

interface WindowData {
  steps_sum: number
  hr_mean: number
  hr_std_dev: number
  hr_max: number
  hr_min: number
  skin_temp_delta: number
  is_sleep_period: boolean
}

interface Classification {
  classification_type: 'single' | 'composition'
  activity?: string
  duration_mins?: number
  met_value?: number
  calories?: number
  composition_mins?: {
    [key: string]: number
  }
}

interface AnalysisResult {
  timestamp: number
  window_data: WindowData
  user_profile: UserProfile
  classification: Classification
}

interface ActivityAnalysisData {
  total_windows: number
  user_profile: UserProfile
  analysis_results: AnalysisResult[]
}

interface ActivityAnalysisChartProps {
  userId: string
  selectedDate: string
}

export function ActivityAnalysisChart({ userId, selectedDate }: ActivityAnalysisChartProps) {
  const [analysisData, setAnalysisData] = useState<ActivityAnalysisData | null>(null)
  const [loading, setLoading] = useState(false)

  // 获取活动分析数据
  const fetchActivityAnalysis = async () => {
    try {
      const selectedDateObj = new Date(selectedDate)
      const startDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0)
      const endDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0)

      const response = await fetch(`/api/health/activity-analysis?userId=${userId}&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      if (!response.ok) {
        throw new Error('Failed to fetch activity analysis')
      }
      
      const data = await response.json()
      setAnalysisData(data.data)
    } catch (error) {
      console.error('获取活动分析数据失败:', error)
      setAnalysisData(null)
    }
  }

  // 生成活动分布图表
  const generateActivityChart = () => {
    if (!analysisData || analysisData.analysis_results.length === 0) return null

    // 活动类型颜色映射
    const activityColors = {
      '睡眠行为': '#6366f1', // 紫色
      '静息行为': '#94a3b8', // 灰色
      '低强度活动': '#22c55e', // 绿色
      '中强度活动': '#f59e0b', // 橙色
      '高强度活动': '#ef4444'  // 红色
    }

    // 准备时间轴数据（每10分钟一个点）
    const timeLabels: string[] = []
    const activityData: any[] = []

    analysisData.analysis_results.forEach((result, index) => {
      const time = new Date(result.timestamp)
      const timeLabel = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`
      timeLabels.push(timeLabel)

      if (result.classification.classification_type === 'single') {
        // 单一活动
        const activity = result.classification.activity || '未知活动'
        activityData.push({
          value: [index, 1],
          itemStyle: {
            color: activityColors[activity as keyof typeof activityColors] || '#64748b'
          },
          activity: activity,
          met: result.classification.met_value || 0,
          windowData: result.window_data
        })
      } else {
        // 混合活动 - 显示主要活动
        const composition = result.classification.composition_mins || {}
        let mainActivity = '低强度活动'
        let maxDuration = 0
        
        Object.entries(composition).forEach(([activity, duration]) => {
          if (duration > maxDuration) {
            maxDuration = duration
            mainActivity = activity
          }
        })

        activityData.push({
          value: [index, 1],
          itemStyle: {
            color: activityColors[mainActivity as keyof typeof activityColors] || '#64748b'
          },
          activity: mainActivity,
          composition: composition,
          windowData: result.window_data
        })
      }
    })

    return {
      title: {
        text: '24小时活动分析',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          const data = params.data
          const time = timeLabels[params.value[0]]
          let tooltipContent = `时间: ${time}<br/>`
          
          const resultIndex = params.value[0]
          const result = analysisData.analysis_results[resultIndex]
          
          if (data.composition) {
            tooltipContent += '混合活动:<br/>'
            Object.entries(data.composition).forEach(([activity, duration]: [string, any]) => {
              if (duration > 0) {
                tooltipContent += `  ${activity}: ${duration.toFixed(1)}分钟<br/>`
              }
            })
            if (result.classification.calories) {
              tooltipContent += `总卡路里: ${result.classification.calories.toFixed(1)}kcal<br/>`
            }
          } else {
            tooltipContent += `活动: ${data.activity}<br/>`
            if (data.met) {
              tooltipContent += `MET值: ${data.met}<br/>`
            }
            if (result.classification.calories) {
              tooltipContent += `卡路里: ${result.classification.calories.toFixed(1)}kcal<br/>`
            }
          }
          
          tooltipContent += `<br/>窗口数据:<br/>`
          tooltipContent += `步数: ${data.windowData.steps_sum}<br/>`
          tooltipContent += `平均心率: ${data.windowData.hr_mean}bpm<br/>`
          tooltipContent += `心率标准差: ${data.windowData.hr_std_dev}<br/>`
          tooltipContent += `皮肤温度变化: ${data.windowData.skin_temp_delta}℃`
          
          return tooltipContent
        }
      },
      legend: {
        data: Object.keys(activityColors),
        top: 30,
        itemWidth: 14,
        itemHeight: 14
      },
      xAxis: {
        type: 'category',
        data: timeLabels,
        axisLabel: {
          interval: 11, // 每2小时显示一个标签（12个10分钟间隔）
          rotate: 45
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f1f5f9',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        show: false,
        min: 0,
        max: 1
      },
      series: [{
        name: '活动类型',
        type: 'scatter',
        data: activityData,
        symbolSize: 20,
        symbol: 'rect', // 使用矩形符号
        itemStyle: {
          borderWidth: 1,
          borderColor: '#fff'
        }
      }],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: '15%'
      }
    }
  }

  // 生成活动统计
  const getActivityStatistics = () => {
    if (!analysisData || analysisData.analysis_results.length === 0) {
      return {
        title: '活动统计',
        stats: [
          { label: '数据窗口', value: '0' },
          { label: '静息心率', value: '无数据' },
          { label: '最大心率', value: '无数据' },
          { label: '心率储备', value: '无数据' }
        ]
      }
    }

    // 统计各种活动的时间分布
    const activityDurations = {
      '睡眠行为': 0,
      '静息行为': 0,
      '低强度活动': 0,
      '中强度活动': 0,
      '高强度活动': 0
    }

    let totalMET = 0
    let totalCalories = 0
    let totalWindows = 0

    analysisData.analysis_results.forEach(result => {
      totalWindows++
      
      if (result.classification.classification_type === 'single') {
        const activity = result.classification.activity || '未知活动'
        const duration = result.classification.duration_mins || 10
        const met = result.classification.met_value || 0
        const calories = result.classification.calories || 0
        
        if (activity in activityDurations) {
          activityDurations[activity as keyof typeof activityDurations] += duration
        }
        totalMET += met * (duration / 60) // MET小时
        totalCalories += calories
      } else {
        const composition = result.classification.composition_mins || {}
        const calories = result.classification.calories || 0
        
        Object.entries(composition).forEach(([activity, duration]) => {
          if (activity in activityDurations) {
            activityDurations[activity as keyof typeof activityDurations] += duration
          }
        })
        // 混合活动的MET估算
        totalMET += 3.0 * (10 / 60) // 假设平均MET为3.0
        totalCalories += calories
      }
    })

    // 找出主要活动
    let mainActivity = '静息行为'
    let maxDuration = 0
    Object.entries(activityDurations).forEach(([activity, duration]) => {
      if (duration > maxDuration) {
        maxDuration = duration
        mainActivity = activity
      }
    })

    const userProfile = analysisData.user_profile

    return {
      title: '活动统计',
      stats: [
        { label: '数据窗口', value: totalWindows.toString() },
        { label: '静息心率', value: `${userProfile.RHR}bpm` },
        { label: '最大心率', value: `${userProfile.MHR}bpm` },
        { label: '心率储备', value: `${userProfile.HRR}bpm` },
        { label: '主要活动', value: mainActivity },
        { label: '总卡路里', value: `${totalCalories.toFixed(1)}kcal` }
      ]
    }
  }

  // 生成活动分布饼图
  const generateActivityPieChart = () => {
    if (!analysisData || analysisData.analysis_results.length === 0) return null

    const activityDurations = {
      '睡眠行为': 0,
      '静息行为': 0,
      '低强度活动': 0,
      '中强度活动': 0,
      '高强度活动': 0
    }

    analysisData.analysis_results.forEach(result => {
      if (result.classification.classification_type === 'single') {
        const activity = result.classification.activity || '未知活动'
        const duration = result.classification.duration_mins || 10
        
        if (activity in activityDurations) {
          activityDurations[activity as keyof typeof activityDurations] += duration
        }
      } else {
        const composition = result.classification.composition_mins || {}
        Object.entries(composition).forEach(([activity, duration]) => {
          if (activity in activityDurations) {
            activityDurations[activity as keyof typeof activityDurations] += duration
          }
        })
      }
    })

    const pieData = Object.entries(activityDurations)
      .filter(([_, duration]) => duration > 0)
      .map(([activity, duration]) => ({
        name: activity,
        value: duration
      }))

    const activityColors = {
      '睡眠行为': '#6366f1',
      '静息行为': '#94a3b8',
      '低强度活动': '#22c55e',
      '中强度活动': '#f59e0b',
      '高强度活动': '#ef4444'
    }

    return {
      title: {
        text: '活动时间分布',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}分钟 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle'
      },
      series: [{
        name: '活动时间',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        data: pieData,
        itemStyle: {
          color: (params: any) => {
            return activityColors[params.name as keyof typeof activityColors] || '#64748b'
          }
        },
        label: {
          formatter: '{b}\n{d}%'
        }
      }]
    }
  }

  useEffect(() => {
    if (!userId || !selectedDate) return
    setLoading(true)
    fetchActivityAnalysis().finally(() => setLoading(false))
  }, [userId, selectedDate])

  const statistics = getActivityStatistics()
  const timelineChart = generateActivityChart()
  const pieChart = generateActivityPieChart()

  return (
    <div className="space-y-4">
      {/* 统计信息 */}
      <Card>
        <CardHeader>
          <CardTitle>{statistics.title}</CardTitle>
          <CardDescription>
            基于10分钟时间窗口的智能活动分析，包含用户个性化生理基准
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {statistics.stats.map((stat, index) => (
              <div key={index} className="text-center p-3 bg-gray-50 rounded-lg">
                <div className="text-2xl font-bold text-gray-900">{stat.value}</div>
                <div className="text-sm text-gray-600">{stat.label}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 时间轴图表 */}
      <Card>
        <CardHeader>
          <CardTitle>24小时活动时间轴</CardTitle>
          <CardDescription>
            每个点代表10分钟时间窗口的活动分类结果
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
            </div>
          ) : timelineChart ? (
            <ReactECharts option={timelineChart} style={{ height: '300px' }} />
          ) : (
            <div className="flex items-center justify-center h-64 text-gray-500">
              暂无数据
            </div>
          )}
        </CardContent>
      </Card>

      {/* 活动分布饼图 */}
      <Card>
        <CardHeader>
          <CardTitle>活动时间分布</CardTitle>
          <CardDescription>
            各类活动的时间占比统计
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
            </div>
          ) : pieChart ? (
            <ReactECharts option={pieChart} style={{ height: '300px' }} />
          ) : (
            <div className="flex items-center justify-center h-64 text-gray-500">
              暂无数据
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
